<template>
  <div id="stock">
    <w-panel-wrap>
      <w-panel-title :title="'库存信息'"></w-panel-title>
      <w-panel>
        <!-- 规格属性表 -->
        <!-- <div class="item">
          <div class="item-group">
            <span class="box-cl-si">选择规格:</span>
            <div class="box">
              <span class="boxColor" @click="insertSpecificationsByGcId(1)">颜色</span>
              <span class="boxColor" @click="insertSpecificationsByGcId(2)">尺码</span>
              <span class="si">如没有规格请点击此处添加(仅支持颜色和尺码)</span>
            </div>
          </div>
        </div> -->
        <div class="item" v-for="(o, $index) in specifications" :key="$index">
          <div class="item-group">
            <div class="label box">{{o.specificationName}}：</div>
            <!--颜色模块  -->
            <div class="box" v-if="o.specificationName == '颜色'">
              <div class="label-c" v-if="csPropertyObject.color.list.length == 0"></div>
              {{colorList}}
              <div class="radio-group mar-l" >
                <!-- <w-checkbox-group v-model="checkRadio" @on-change="onColorChange"> -->
                  <!-- 系统自带的颜色信息，不可删除 -->
                  <!-- <span class="c-radio" v-for="(item, index) in colorList" :key="index" v-show="colorList.length > 0">
                    <w-checkbox-item :label="item.specpropertyId" :result="item">{{item.specpropertyName}}</w-checkbox-item>
                  </span>
                <span class="c-radio s-d  box" v-for="(item,index) in csPropertyObject.color.list" :key="index">
                  <w-checkbox-item :label="item.specpropertyId" :result="item">{{item.specpropertyName}}</w-checkbox-item>
                  <i v-show="true" @click="deleteById(item.specpropertyId, '颜色')">
                    <img src="../../../assets/delect.png" style="width: 20px;height: 20px;">
                  </i>
                </span> -->
                <!-- </w-checkbox-group> -->
                <span class="c-radio s-d  box" v-for="(item,index) in csPropertyObject.color.list" :key="index">
                  <w-radio :name="'color'" :label="item.specpropertyId" @on-radio="onRadio(item)">{{item.specpropertyName}}</w-radio>
                  <i v-show="true" @click="deleteById(item.specpropertyId, '颜色')">
                    <img src="../../../assets/delect.png" style="width: 20px;height: 20px;">
                  </i>
                </span>
              </div>
              <div class="submit mar-l" v-if="csPropertyObject.color.toggle==true" >
                <w-input :holder="'请输入'" v-model="csPropertyObject.color.addSpescName" :validate="false"></w-input>&nbsp;
                <button class="btn main btn-c" style="margin-top:7px;" @click="insetSpecproperty('颜色')">提交</button>
              </div>
              <div class="quite">
                没有找到{{o.specificationName}}？
              </div>
              <button v-if="csPropertyObject.color.toggle==false" class="btn main btn-c" style="margin-top:7px;margin-left:99px;" @click="csPropertyObject.color.toggle=true">立即添加</button>
            </div>
            <!--其他规格属性模块  -->
            <div class="box" v-else>
              <div class="label-c" v-if="csPropertyObject.size.list.length == 0">
              </div>
              <div class="s-radio mar-l">
                <w-checkbox-group v-model="checkSize" @on-change="onColorChange">
                  <span class="s-d box size" v-for="(item, index) in csPropertyObject.size.list" :key="index">
                    <w-checkbox-item :label="item.specpropertyId" :result="item">{{item.specpropertyName}}</w-checkbox-item>
                    <i v-show="true" @click="deleteById(item.specpropertyId, '尺码')" class="bacI">
                      <img style="width: 20px;" src="../../../assets/delect.png">
                    </i>
                  </span>
                </w-checkbox-group>
              </div>
              <div class="submit mar-l" v-if="csPropertyObject.size.toggle==true" >
                <w-input :holder="'请输入'" v-model="csPropertyObject.size.addSpescName" :validate="false"></w-input>&nbsp;
                <button class="btn main btn-c" style="margin-top:7px;" @click="insetSpecproperty('尺码')">提交</button>
              </div>
              <div class="quite">
                没有找到{{o.specificationName}}？
              </div>
              <button v-if="csPropertyObject.size.toggle==false" class="btn main btn-c mar-l" style="margin-top:7px;" @click="csPropertyObject.size.toggle=true">立即添加</button>
            </div>
          </div>
        </div>
        <div class="item">
          <div class="item-group">
            <span class="label box"></span>
            <div class="box  mar-l">
              <button class="btn main btn-c" style="margin-top:7px;margin-bottom:54px;" @click="addGroup">立即添加组合</button>
              <table v-if="goodsDetailList.length > 0">
                <thead class="thead">
                  <tr>
                    <td v-for="item in columns" v-text="item.title"></td>
                  </tr>
                </thead>
                <sku-group v-for="(item, index) in goodsDetailList" :index="index" :key="index" :specs="item" @ng-input="setNewProperty" @ng-delGroup="delGroup"></sku-group>
              </table>
            </div>
          </div>
        </div>
        <w-panel-title :title="'设置发货量'"></w-panel-title>
        <div class="item">
          <div class="item-group">
            <span class="label box label-h">发货量:</span>
            <div class="box box-w">
              <div class="box">
                <w-input v-model="crowdfundingCount" :validate="false" rule="isEmpty" error="发货量不能为空"></w-input>
              </div>
              &nbsp;件
              <div class="tip">
                <span class="label-c">拼货量必须大于等于发货量，拼团才能成功，否则拼团失败,请谨慎设置
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="item" style="border:0;">
          <div class="item-group">
            <span class="label box label-h"></span>
            <div class="box mar-l">
              <button class="btn main" type="button" @click="onPrev">上一步</button>
              <button class="btn main" @click="onNext">下一步</button>
            </div>
          </div>
        </div>
      </w-panel>
    </w-panel-wrap>
  </div>
</template>
<script>
import { apiGoods, queryGoodsRulesById } from '../../../common/api'
import skuGroup from './SkuGroup.vue'
import { storage } from 'js/util'

const RULE = {
  '颜色': 'color',
  '尺码': 'size'
}
export default {
  data() {
    return {
      // 商品二级分类
      goodsTwoId: '' || storage.get('goodsTwoId'),
      // 商品分类Id
      gcId: '' || parseInt(this.$route.params.id),
      colorList: [], // 系统原有规格颜色信息
      sizeList: [], // 系统原有尺寸信息
      // 商品规格结果
      specifications: [],
      specificationName1: '',
      specificationName2: '',
      crowdfundingCount: '',
      // 规格属性中颜色 尺寸集合
      csPropertyObject: {
        'color': {
          list: [],
          // 新增规格属性名称
          addSpescName: '',
          // 规格的Id
          superId: '',
          toggle: false
        },
        'size': {
          list: [],
          addSpescName: '',
          superId: '',
          toggle: false
        }
      },
      checkSize: [],
      checkRadio: {},
      goodsDetailList: [],
      // 表格头
      columns: [
        { title: '颜色', width: '10%' },
        { title: '最低发货量', width: '15%' },
        { title: '尺码', width: '10%' },
        { title: '库存（期货不需设置）', width: '20%' },
        { title: '采购商最低起购量', width: '20%' },
        { title: '商品货号', width: '15%' },
        { title: '', width: 'auto' }
      ]
    }
  },
  created() {
    let _this = this
    _this.getSpecifications()
    setTimeout(() => {
      if (_this.$store.getters.goodsInventoryDetail && _this.$store.getters.goodsInventoryDetail != null && _this.$store.getters.goodsInventoryDetail != '') {
        let goods = JSON.parse(_this.$store.getters.goodsInventoryDetail)
        if (typeof (goods) == 'string') {
          JSON.parse(goods).forEach(function(element, index) {
            _this.goodsDetailList.push(element)
          })
        } else {
          goods.forEach(function(element, index) {
            _this.goodsDetailList.push(element)
          })
        }
      }
      if (sessionStorage.getItem('crowdfundingCount')) {
        this.crowdfundingCount = sessionStorage.getItem('crowdfundingCount')
      }
    }, 1000)
    this.getPtysProperty()
  },
  components: {
    skuGroup
  },
  methods: {
    /**
     * 设置新的属性信息
     */
    setNewProperty(value) {
      this.goodsDetailList[value.index] = value.data
    },
    // 分类下商品规格查询
    getSpecifications() {
      let json = {
        gcId: this.$route.params.id,
        storeId: this.$store.getters.storeId,
        accessToken: this.$store.getters.token
      }
      apiGoods.getSpecifications(json).then((resp) => {
        if (resp.specificationList.length > 0) {
          this.specifications = resp.specificationList.slice(0, 2)
          this.specificationName1 = resp.specificationList[0].specificationName
          this.specificationName2 = resp.specificationList[1].specificationName
          this.specifications.forEach((o) => {
            // 保存规格Id
            this.csPropertyObject[RULE[o.specificationName]].superId = o.specificationId
            this.getSpecproperty(o.specificationId, o.specificationName)
          })
        }
      })
    },
    // 激活规格
    activeSpesc(item, index) {
      let active = !item.isSelected
      this.$set(item, 'isSelected', active)
    },
    //  根据specificationId规格id 获取属性规格详情
    getSpecproperty(specificationId, name) {
      let json = {
        specificationId: specificationId
      }
      apiGoods.getSpecproperty(json).then((resp) => {
        this.csPropertyObject[RULE[name]].list = resp.specpropertyList
        if (name == '颜色') {
          const colorSpescList = this.$store.getters.colorSpescList
          for (let spec in resp.specpropertyList) {
            let oSpec = resp.specpropertyList[spec]
            for (let color in colorSpescList) {
              let oColor = colorSpescList[color]
              if (oSpec.specpropertyId == oColor.specpropertyId) {
                resp.specpropertyList[spec] = colorSpescList[color]
                break
              }
            }
          }
          this.$store.dispatch('updateColorSpesc', resp.specpropertyList)
        }
      })
    },
    // 系统原有规格属性
    getPtysProperty() {
      let gcIdList = {
          goodsTwoId: this.goodsTwoId,
          goodsSecId: this.gcId
      }
      apiGoods.getPtysProperty(gcIdList).then(data => {
        if (data.colour.length != 0 || data.size != 0) {
          // 颜色信息
          this.colorList = data.colour
          this.sizeList = data.size // 尺寸信息
        }
      })
    },
    // 新增规格属性详情
    insetSpecproperty(name) {
      if (name == '颜色') {
        console.log(this.csPropertyObject[RULE[name]].addSpescName)
        let reg = /^[\u4e00-\u9fa5]+$/
        if (!reg.test(this.csPropertyObject[RULE[name]].addSpescName) || this.csPropertyObject[RULE[name]].addSpescName.length > 5) {
          this.$toast('必须中文且长度不能大于5')
          return
        }
      }
      if (name == '尺码') {
        let reg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/
        if (!reg.test(this.csPropertyObject[RULE[name]].addSpescName) || this.csPropertyObject[RULE[name]].addSpescName.length > 5) {
          this.$toast('不能包含特殊字符且长度不能大于5')
          return
        }
      }
      let specificationId = ''
      this.specifications.forEach((item) => {
        if (item.specificationName == name) {
          specificationId = item.specificationId
          return
        }
      })
      if (name == '尺码' && !this.csPropertyObject.size.addSpescName) {
        return
      }
      if (name == '颜色' && !this.csPropertyObject.color.addSpescName) {
        return
      }
      let json = {
        specificationId: specificationId,
        specpropertyName: this.csPropertyObject[RULE[name]].addSpescName
      }
      apiGoods.insetSpecproperty(json).then((resp) => {
        this.csPropertyObject[RULE[name]].addSpescName = ''
        this.getSpecproperty(specificationId, name)
      })
    },
    // 删除颜色记录 尺寸记录
    deleteById(id, name) {
      let json = {
        specpropertyId: id
      }
      apiGoods.deleteSpecpropertyById(json).then((resp) => {
        // 查询属性详情
        this.getSpecproperty(this.csPropertyObject[RULE[name]].superId, name)
      })
    },
    onRadio(item) {
      this.checkRadio = item
      this.checkSize = []
      this.$set(this.checkRadio, 'specpropertyCrowdSum', '')
      this.$set(this.checkRadio, 'specpropertyList', [])
    },
    // onColorChange(checkModel) {
    //   checkModel.forEach(item => {
    //     this.$set(item, 'specpropertyCrowdSum', '')
    //     this.$set(item, 'specpropertyList', []) // 设置该颜色下的尺码信息组
    //   })
    //   this.checkRadio = checkModel
    //   console.log(1111111, checkModel)
    // },
    onColorChange(checkModel) {
      checkModel.forEach(item => {
        this.$set(item, 'specpropertyInventCount', '')
        this.$set(item, 'specpropertySmallCount', '')
      })
      this.checkSize = checkModel
    },
    // 删除组合
    delGroup(sIndex) {
      if (sIndex.key == 1) {
        this.goodsDetailList[sIndex.index] = sIndex.value
      } else {
        this.goodsDetailList.splice(sIndex.index, 1)
      }
    },
    // 立即组合
    addGroup() {
      let _this = this
      if (this.checkRadio == undefined || this.checkRadio == {}) {
        this.$toast('请选择规格颜色')
        return
      }
      if (this.checkSize.length == 0) {
        this.$toast('请选择组合')
        return
      }
      this.checkRadio.specpropertyList = this.checkSize
      if (this.goodsDetailList.length == 0) {
        this.goodsDetailList.push(this.checkRadio)
      } else {
        for (var i = 0; i < this.goodsDetailList.length; i++) {
          if (this.goodsDetailList[i].specpropertyId == this.checkRadio.specpropertyId) {
            _this.checkRadio.specpropertyList.forEach((ele, index) => {
              let flag = true
              _this.goodsDetailList[i].specpropertyList.forEach((ment, index) => {
                if (ment.specpropertyId == ele.specpropertyId) {
                  flag = false
                }
              })
              if (flag) {
                _this.goodsDetailList[i].specpropertyList.push(ele)
              }
            })
            return
          }
        }
        this.goodsDetailList.push(this.checkRadio)
      }
    },
    onPrev() {
      this.$store.commit('intoThisPage', 3)
      this.$store.commit('intoNextPage', 3)
      let index = this.$parent.$parent.curIndex
      if (index == 0) {
        this.$router.go(-1)
      } else {
        this.$parent.$parent.onChangeContent(index - 1)
        if (typeof (this.$route.params.gdId) == 'undefined') {
          this.$store.commit('intoThisPage', 0)
        }
      }
    },
    // 库存信息提交
    onNext() {
      this.$store.commit('intoThisPage', 1)
      if (this.goodsDetailList.length == 0 || this.goodsDetailList[0].specpropertyList.length == 0) {
        this.$toast('请选择组合')
        return
      }
      if (!this.crowdfundingCount || this.crowdfundingCount == '') {
        this.$toast('发货量必填')
        return
      }
      let _this = this
      let test = true
      let propertyCrowdSum = ''
      _this.goodsDetailList.forEach(function(goodDetail, index) {
        if (!goodDetail.specpropertyCrowdSum || goodDetail.specpropertyCrowdSum == '') {
          _this.$toast('最低发货量不能为空')
          test = false
          return
        }
        if (_this.goodsDetailList.length == 1) {
          propertyCrowdSum = goodDetail.specpropertyCrowdSum
        }
        if (index > 0 && _this.goodsDetailList[index].specpropertyCrowdSum > _this.goodsDetailList[index - 1].specpropertyCrowdSum) {
            propertyCrowdSum = _this.goodsDetailList[index - 1].specpropertyCrowdSum
          } else if (index > 0 && _this.goodsDetailList[index].specpropertyCrowdSum <= _this.goodsDetailList[index - 1].specpropertyCrowdSum) {
            propertyCrowdSum = _this.goodsDetailList[index].specpropertyCrowdSum
          }
        if (propertyCrowdSum * 1 > _this.crowdfundingCount) {
          _this.$toast('最低发货量不能大于总发货量')
          test = false
          return
        }
        goodDetail.specpropertyList.forEach(function(element, index) {
          if (!element.specpropertySmallCount || element.specpropertySmallCount == '') {
            _this.$toast('最低购买量不能为空')
            test = false
            return
          } else if (sessionStorage.getItem('goodsNumType') == 1 && !element.specpropertyInventCount) {
            _this.$toast('现货的库存必填')
            test = false
            return
          } else if (element.specpropertyInventCount && element.specpropertyInventCount != '') {
            if (element.specpropertySmallCount * 1 > element.specpropertyInventCount * 1) {
              _this.$toast('最低购买量不能大于库存')
              test = false
              return
            }
          }
          if (!element.specpropertySerial || element.specpropertySerial == '') {
            _this.$toast('商品货号不能为空')
            test = false
            return
          }
        })
      })
      if (test) {
         let json = {
          accessToken: this.$store.getters.token,
          goodsStoreId: this.$store.getters.storeId,
          goodsId: this.$store.getters.goodsId || this.$route.params.gdId,
          goodsDetailList: this.goodsDetailList,
          crowdfundingCount: this.crowdfundingCount
        }
        apiGoods.goodsInsertSecond(json).then((resp) => {
          this.$toast('提交成功')
          let _this = this
          if (!this.$store.getters.goodsDetailsList[0] || !this.$store.getters.goodsDetailsList[0].specpropertyPhotoPath) {
            this.$store.commit('goodsDetailsList', this.goodsDetailList)
          }
          if (this.$store.getters.goodsDetailsList && this.$store.getters.goodsDetailsList != this.goodsDetailList) {
            this.goodsDetailList.forEach(function(element, index) {
              if (element.specpropertyImg) {
                _this.$set(element, 'specpropertyPhotoPath', _this.$store.getters.photoGspUrl)
                _this.$set(element, 'specpropertyPhotoUrl', element.specpropertyImg)
              }
            })
            this.$store.commit('goodsDetailsList', this.goodsDetailList)
          }
          setTimeout(() => {
            let index = this.$parent.$parent.curIndex
            this.$parent.$parent.onChangeContent(index + 1)
            if (typeof (this.$route.params.gdId) == 'undefined') {
              this.$store.commit('intoThisPage', 0)
            }
          }, 2000)
        })
      }
    }
  }
}
</script>
<style lang="scss">
#stock {
  .error-tip {
    padding-right: 100px;
    position: absolute;
    left: 15px;
  } 
  .item {
    padding: 20px 0 20px 144px;
    border-bottom: 1px dashed #47BDF4;
    font-size: 14px;
    width: 100%;
    position: relative;
    .item-group {
      .label {
        min-width: 99px;
        text-align: right;
        color: #999;
        position: absolute;
        left:144px;
        top:22px;
      }
      .item-c {
        color: #666;
      }
      .mar-l{
        margin-left: 99px;
      }
      .tip {
        margin-top: 15px;
      }
      .spesc {
        color: #666;
        border: 1px solid;
        height: 31px;
        width: 91px;
        border-radius: 3px;
        display: inline-block;
        line-height: 31px;
        text-align: center;
        position: relative;
        margin-bottom: 15px !important;
        margin-right: 15px !important;
        cursor: pointer;
      }
      .active {
        color: #F20685
      }
      .c-radio {
        margin-right: 20px;
        margin-bottom: 20px;
        .m-radio input:checked+.radio-btn[data-v-a5d73c30] {
          border-color: #47BDF4;
          box-shadow: inset 0 0 0 4px #47BDF4
        }
        i {
          right: -17px;
          top: -14px;
        }
        strong {
          color: #F20685;
        }
        .upload {
          width: 60px;
          height: 60px;
          vertical-align: middle;
          margin-right: 69px;
          .single-upload-wrap {
            position: relative;
            display: block;
            height: 60px;
            border-radius: 4px;
            border: 2px dashed #e6e6e6;
            background-color: #fafafa;
            background-image: url();
            background-repeat: no-repeat;
            background-position: center center;
            background-size: 44% 60%;
            cursor: pointer;
            .img-preview {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              background: #fff;
            }
            &.disabled {
              cursor: default;
              background-size: 60% 20%;
              background-repeat: no-repeat;
              background-position: center center;
              background-image: url();
            }
            input {
              width: 0;
              height: 0;
              opacity: 0;
            }
          }
        }
        img {
          width: 60px;
          height: 60px;
          display: inline-block;
          vertical-align: middle;
        }
        margin-bottom: 46px;
      }
      .s-radio {
        .m-checkbox input:checked+.check-btn{
          border-color: #47BDF4;
          background: #47BDF4;
        }
        .size {
          margin-bottom: 15px;
          margin-right: 30px;
          i {
            right: -17px;
            top: -14px;
          }
        }
      }
    }
    .label-c {
      color: #999;
    }
    .box-cl-si {
      color: #999;
      margin-left: 35px;
    }
    .si {
      color: #999;
      font-size: 12px;
    }
    .box {
      display: inline-block;
      .w-input {
        display: inline-block;
      }
      .quite {
        color: #999;
        margin-top: 30px;
        margin-left: 100px;
      }
      .boxColor {
        display: inline-block;
        width: 90px;
        height: 30px;
        border:1px solid #999;
        border-radius: 5px;
        text-align: center;
        line-height: 28px;
      }
    }
    .btn-c {
      background-color: #4BBFF4;
    }

    .s-d {
      position: relative;
      i {
        // content: 'x';
        width: 20px;
        height: 20px;
        border-radius: 10px;

        color: #fff;
        text-align: center;
        line-height: 20px;
        display: inline-block;
        position: absolute;
        top: -7px;
        right: -10px;
        z-index: 8;
        background-img:url('../../../assets/delect.png');
        background-position: center;
        background-repeat: no-repeat;
      }
    }
  }
  table {
    border: 1px solid #e6e6e6;
    max-width: 800px;
    .thead {
      background-color: #f7f7f7;
      tr {
        height: 50px;
        text-align: center;
        td {
          min-width: 80px;
        }
      }
    }
    td {
      height: 50px;
      text-align: center;
    }
  }
  .box-w {
    margin-left: 110px;
  }
}
</style>